import {
  defineComponent,
  ref,
  reactive,
  onMounted,
  onUnmounted,
  watch,
} from 'vue'
import './index.less'
import PropTypes from '@/utils/PropTypes'
import {
  MapEventConfigType,
  MarkerClickTargetType,
  PolylineType,
  PolylineSateType,
  DrawOptionType,
} from './type'
import { createMarker } from './marker'
import {
  Driving,
  startAnimation,
  endAnimation,
  pauseAnimation,
  resumeAnimation,
  forwardAnimation,
  toBackAnimation,
} from './moveAlone'
import { MarkerType } from './type'
// import AMapLoader from '@amap/amap-jsapi-loader'
export default defineComponent({
  name: 'AMapCom',
  props: {
    centerCity: PropTypes.string(),
    markers: PropTypes.array<MarkerType>().def([]),
    centerMrk: PropTypes.any(),
    polyline: PropTypes.object<PolylineType>(),
    polylineState: PropTypes.object<PolylineSateType>().def({
      speed: 10000,
      isPlay: false,
    }),
    playState: PropTypes.number().def(0),
    drawOption: PropTypes.object<DrawOptionType>().def({
      isShowDrawTool: false,
      isDrawData: false,
      drawData: [],
    }),
    searchAddress: PropTypes.string(),
    searchMarkerClick: PropTypes.func<(e: MouseEvent) => void>(),
    isHistoryData: PropTypes.bool().def(false),
  },
  emits: [
    'update:drawPolyPaths',
    'update:currentMarkerId',
    'update:playState',
    'update:playComplete',
  ],
  setup(props, { emit }) {
    const { AMap } = window as any
    const cluster = ref<any>()
    const path = ref<any[]>([])
    const drivingInfo = reactive<any>({
      section: 0,
      sectionIndex: 0,
      currentIndex: 0,
      isReadyComplete: false,
    })
    const currentMap = ref<any>()
    const ininMap = () => {
      currentMap.value = new AMap.Map('mapContainer', {
        viewMode: '2D', // 默认使用 2D 模式
        zoom: 10, //初始化地图层级
        center: [116.397428, 39.90923], //初始化地图中心点
      })
    }
    onMounted(() => {
      // 插件方式
      // AMapLoader.load({
      //   key: 'c174c14e05791da4418a13ca29b9fd8c', // 申请好的Web端开发者Key，首次调用 load 时必填
      //   version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      //   plugins: [
      //     'AMap.Geocoder',
      //     'AMap.MarkerClusterer',
      //     'AMap.MoveAnimation',
      //   ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      //   AMapUI: {
      //     version: '1.1',
      //     plugins: ['overlay/SimpleMarker'],
      //   },
      // })
      //   .then((AMap) => {
      //     currentMap.value = new AMap.Map('mapContainer', {
      //       resizeEnable: true,
      //       zoom: 11, //级别
      //       center: [113.663221, 34.7568711], //中心点坐标
      //       viewMode: '2D', //使用3D视图
      //     })
      //     createMarker(currentMap.value, AMap, markerRefs.value)
      //     Driving(
      //       currentMap.value,
      //       AMap,
      //       path,
      //       props.playOptions,
      //       drivingInfo,
      //       content.value,
      //     )
      //   })
      //   .catch((e) => {
      //     console.log(e)
      //   })
      /**
       * cdn引入的方式， 这里为了全局使用AMap,采用cdn 引入
       */
      ininMap()
    })

    /**
     * 点击marker事件
     */
    function clickMarker(target: MarkerClickTargetType) {
      console.log(target, '58858')
      emit('update:currentMarkerId', target)
    }
    onUnmounted(() => {
      currentMap.value?.destroy()
      currentMap.value = null
      console.log(currentMap.value, '销毁地图')
    })
    watch(
      () => props.centerMrk,
      (newVal) => {
        if (newVal) {
          currentMap.value?.setCenter(newVal.lnglat)
        }
      },
    )
    watch(
      () => props.markers.length,
      (val, oldval) => {
        if (props.markers.length > 0) {
          if (!currentMap.value) return
          currentMap.value && currentMap.value.clearMap()
          props.markers.forEach((v) => (v.onClick = clickMarker))
          // currentMap.value.clearMap()
          if (cluster.value) {
            cluster.value.setData([])
            cluster.value.setMap(null)
            setTimeout(() => {
              currentMap.value && cluster.value.setData(props.markers)
            }, 200)
          }
          createMarker(currentMap.value, props.markers, cluster)
        }
      },
    )
    watch(
      () => props.isHistoryData,
      () => {
        props.markers.forEach((v) => {
          console.log(v, '--v---')
          currentMap.value.remove(v)
        })
        currentMap.value && currentMap.value.clearMap()
      },
    )
    watch(
      () => [props.polyline?.paths.length, props.polyline?.content.length],
      () => {
        path.value = props.polyline?.paths || []
        const content =
          props.polyline?.content && props.polyline?.content.length > 0
            ? props.polyline?.content
            : []
        if (props.polyline?.paths && props.polyline?.paths.length > 0) {
          endAnimation()
          currentMap.value.clearMap()
          AMap.plugin('AMap.MoveAnimation', function () {
            // 加载完 AMap.MoveAnimation 插件以后，创建一个 Marker 实例
            Driving(
              currentMap.value,
              AMap,
              path.value,
              props.polylineState.speed,
              drivingInfo,
              content,
            )
          })
        }
      },
    )
    watch(
      () => [props.polylineState.isPlay, props.polylineState.speed],
      () => {
        if (path.value.length <= 0) {
          emit('update:playComplete', false)
          return
        }
        if (props.polylineState.isPlay) {
          if (drivingInfo.currentIndex === path.value.length - 2) {
            startAnimation(path.value, 0)
          } else {
            startAnimation(path.value)
          }
        } else {
          pauseAnimation()
        }
      },
    )
    watch(
      () => drivingInfo.sectionIndex,
      () => {
        if (drivingInfo.sectionIndex === path.value.length)
          emit('update:playComplete', false)
      },
    )
    watch(
      () => props.playState,
      (val) => {
        if (val > 0) {
          endAnimation()
          forwardAnimation(path.value)
          emit('update:playState', 0)
          if (!props.polylineState.isPlay) return
          setTimeout(() => {
            if (drivingInfo.currentIndex < path.value.length - 1) {
              startAnimation(path.value)
            } else {
              startAnimation(path.value, 0)
            }
          }, 1000)
        }
        if (val < 0) {
          if (drivingInfo.currentIndex > 0) {
            endAnimation()
            toBackAnimation(path.value)
            emit('update:playState', 0)
            if (!props.polylineState.isPlay) return
            setTimeout(() => {
              startAnimation(path.value)
            }, 1000)
          }
        }
      },
    )

    return () => <div id="mapContainer"></div>
  },
})
